package cc.wd.demo.blockchain.model;

import cc.wd.demo.blockchain.utils.SecureUtil;
import lombok.Getter;

/**
 * @author wudi
 * @date 2018/8/28
 */
@Getter
public class Block {
    private String hash;
    private String previousHash;
    private String data; //数据
    private long timeStamp; //时间戳
    private int nonce;//随机数

    /**
     * 构造函数
     *
     * @param data
     * @param previousHash
     */
    public Block(String data, String previousHash) {
        this.data = data;
        this.previousHash = previousHash;
        this.timeStamp = System.currentTimeMillis();
        this.hash = calculateHash();
    }

    /**
     * 计算hash值（把新增的随机数也计算在内）
     */
    public String calculateHash() {
        return SecureUtil.Sha256(
                previousHash +
                        Long.toString(timeStamp) +
                        Integer.toString(nonce) +
                        data
        );
    }

    public void mineBlock(int difficulty) {
        //创建一个string值由难度的位数来决定
        String target = new String(new char[difficulty]).replace('\0', '0');
        while (!hash.substring(0, difficulty).equals(target)) {
            nonce++;
            hash = calculateHash();
        }
        System.out.println("Block Mined!!! : " + hash);
    }


}
